package com.work.app.service;


import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.wap.models.AlipayTradeWapPayResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author hjj
 * @Time 2024/3/10 10:55
 */
@Service
public class AlipayService {
    @Value("${alipay.returnUrl}")
    private String returnUrl;
    @Value("${alipay.quitUrl}")
    private String quitUrl;


    /**
     * 生成支付表单
     * @param subject 交易标签名
     * @param money     交易金额
     * @return 表单字符串
     * @throws Exception
     */
    public String toPay(String subject, BigDecimal money)throws Exception{
        AlipayTradeWapPayResponse response = Factory.Payment.Wap()
                .pay(subject, this.generateTradeNo(), String.valueOf(money), quitUrl,returnUrl);
        String payForm = null;
        if (ResponseChecker.success(response)) {
            payForm = response.getBody();
            //System.out.println(payForm);
        }
        return payForm;
    }

    /**
     * 通过时间生成外部订单号
     * @return
     */
    private String generateTradeNo(){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        return LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);
    }
    

}
